import axios from 'axios';
import qs from 'qs';
// const Baseurl = window.location.origin;
// const Baseurl = `http://sale.91jch.com`;

const instance = axios.create({
  timeout: 60 * 1000 * 2, //请求超时
  // baseURL: Baseurl //接口地址
});

// 请求拦截
instance.interceptors.request.use(
  function (config) {
    // config.headers.authorization = "Bearer " + getToken(); // 设置请求头（格式不一定是这样）
    // console.log(config);
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

//响应拦截
instance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    console.dir(error);
    return Promise.reject(error);
  }
);

function Getdata(url, params) {
  return new Promise(function (resolve, reject) {
    params = {
      params: params,
    };
    instance
      .get(`/${url}`, params)
      .then(function (res) {
        resolve(res);
      })
      .catch(function (err) {
        console.log(err);
        reject(err);
      });
  });
}

function Postdata(url, params) {
  return new Promise(function (resolve, reject) {
    instance
      .post(`/${url}`, qs.stringify(params))
      .then(function (res) {
        resolve(res);
      })
      .catch(function (err) {
        reject(err);
      });
  });
}

const formatPostData = function formatPostData(url, formData) {
  return new Promise(function (resolve, reject) {
    instance({
      url: `/${url}`,
      method: 'post',
      data: formData,
    })
      .then(function (res) {
        resolve(res);
      })
      .catch(function (err) {
        reject(err);
      });
  });
};

const getCookie = function getCookie(sName) {
  var aCookie = document.cookie.split('; ');

  for (var i = 0; i < aCookie.length; i++) {
    var aCrumb = aCookie[i].split('=');
    if (sName == aCrumb[0]) return decodeURIComponent(aCrumb[1]);
  }
  return null;
};
export default { formatPostData, Postdata, Getdata, getCookie };
